package com.example.handlerdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.squareup.leakcanary.RefWatcher;

import java.lang.ref.WeakReference;

public class SecondActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    private Handler myHandler;
    private Activity activity;

    private MyEventListener listener = new MyEventListener() {
        @Override
        public void handleMessage(Message msg) {
            Log.e(TAG, "handleMessage: ");
            if (activity == null) {
                Log.e(TAG, "handleMessage: activity == null");
            } else {
                Log.e(TAG, "handleMessage: activity != null");
            }

        }
    };

    private void test() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;

        //1.外部Handler + 接口回调方式
        myHandler = new MyHandler(listener);

        myHandler = new MyHandler(new MyEventListener() {
            @Override
            public void handleMessage(Message msg) {
                test();
            }
        });

        //2.静态内部类 ＋ 弱引用
        //myHandler = new MyClass(this);

        //3.静态内部类
        /*
        myHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.e(TAG, "handleMessage: ");
                super.handleMessage(msg);
            }
        };*/

        findViewById(R.id.btn_tuijian).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myHandler.sendEmptyMessageDelayed(100, 10000);
            }
        });
    }

    @Override
    protected void onDestroy() {
        Log.e(TAG, "onDestroy: "  + SecondActivity.this.hashCode());
        super.onDestroy();
        RefWatcher refWatcher = MyApplication.getRefWatcher(this);
        if (refWatcher != null) {
            refWatcher.watch(this);
        }
    }

    static class MyClass extends Handler {
        private WeakReference<Activity> mWeakReference;
        public MyClass(Activity activity) {
            mWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            Log.e(TAG, "handleMessage: ");
            super.handleMessage(msg);
            Activity activity = mWeakReference.get();
            if (activity != null) {
                Log.e(TAG, "handleMessage: activity != null");
            } else {
                Log.e(TAG, "handleMessage: activity == null");
            }
        }
    }
}
